/**
 * icons - jQuery icons plugin
 * 
 * show all icons defined in css
 * 
 * @date 2013/1/17
 * @author hu shaolei
 * 
 * Parameters: href:'css/icon.css', num:5 //每行个数
 * 
 * Dependencies: jquery.form.js
 * 
 */
(function($) {
	function getCls(str) {
		var start = str.indexOf('.');
		var end = str.indexOf('{');
		var cls = $.trim(str.substring(start + 1, end));
		return cls;
	}

	function getTd(str, index) {
		str = getCls(str);
		return "<td>" + (index + 1) + "</td><td width='100px'>" + str
				+ "</td><td width='50px'><span class='icon " + str
				+ "'></span></td>";
	}
	function getEmptyTd(index) {
		var td = "";
		for ( var i = 0; i < index; ++i) {
			td = td + "<td></td><td></td><td></td>";
			;
		}
		return td;
	}

	$.fn.icons = function(options) {
		var opts = $.extend({}, $.fn.icons.defaults, options);

		var form = $('<form action="' + opts.href + '"></form>').appendTo(
				$(this));
		var table = $('<table></table>').appendTo($(this));
		form.ajaxSubmit({
			success : function(data) {
				var a = data.split('}');
				var i = 0;
				for (; i < a.length - opts.num; i = i + opts.num) {
					var tds = getTd(a[i], i);
					for ( var j = i + 1; j < i + opts.num; ++j) {
						tds = tds + getTd(a[j], j);
					}
					$("<tr>" + tds + "</tr>").appendTo(table);
				}
				var lastTd = "";
				while (i < a.length - 1) {
					lastTd = lastTd + getTd(a[i], i);
					++i;
				}
				if ((a.length-1) % opts.num != 0) {
					lastTd = lastTd
							+ getEmptyTd(opts.num - (a.length-1) % opts.num);
				}

				$("<tr>" + lastTd + "</tr>").appendTo(table);
			}
		});

		//form.submit();
	};

	$.fn.icons.defaults = {
		href : 'css/icon.css',
		num : 5
	};
})(jQuery);